package util;


import bean.DauInfo;
import bean.PageLog;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class MyBeanUtils {
    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
        PageLog pageLog = new PageLog("mid1001" , "uid101" , "prov101" , null ,null ,null ,null ,null ,null ,null ,null ,null ,null ,0L ,null ,123456L);
        DauInfo  dauInfo = new DauInfo();
        System.out.println(dauInfo.toString());
        BeanUtils.copyProperties(dauInfo,pageLog);
        System.out.println(dauInfo.toString());
    }
    public static void copyProperties(Object srcObj, Object destObj){
        if(srcObj == null || destObj == null) {
            return;
        }
        //获取到srcObj中所有的属性
        Field[] srcFields = srcObj.getClass().getDeclaredFields();
        //处理每个属性的拷贝
        for(Field srcField : srcFields) {
            try{
                String getMethodName = srcField.getName();
                String setMethodName = srcField.getName() + "_$eq";
                //从srcObj中获取get方法对象，
                Method getMethod = srcObj.getClass().getDeclaredMethod(getMethodName);
                Method setMethod = destObj.getClass().getDeclaredMethod(setMethodName,srcField.getType());
                //忽略val属性
                Field destField = destObj.getClass().getDeclaredField(srcField.getName());
                if(destField.getModifiers() == (Modifier.FINAL)){
                    break;
                }
                //调用get方法获取到srcObj属性的值， 再调用set方法将获取到的属性值赋值给destObj的属性
                setMethod.invoke(destObj, getMethod.invoke(srcObj));
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            } catch (NoSuchFieldException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
